<!--
 * @Author: xiaxia
 * @Description: 
 * @Date: 2024-06-24 16:34:11
 * @LastEditTime: 2024-07-09 16:38:05
 * @FilePath: \project\src\views\acl\role\index.vue
-->
<template>
  <div>
    <el-card>
      <el-form :inline="true" :model="roleSearch" class="roleForm">
        <el-form-item label="用户名">
          <el-input v-model="roleSearch.roleName" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="hSearch">查询</el-button>
          <el-button @click="hReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top:10px">
      <el-button type="primary" @click="hAdd" icon="plus">添加角色</el-button>
      <el-table :data="roleData" border style="margin: 10px 0">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="55" />
        <el-table-column prop="id" label="id" width="100" />
        <el-table-column prop="roleName" label="角色名称" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip />
        <el-table-column prop="updateTime" label="更新时间" show-overflow-tooltip />
        <el-table-column label="操作" width="280">
          <template #="{row}">
            <el-button size="small" @click="hSetRole(row)" icon="user">分配权限</el-button>
            <el-button size="small" @click="hEdit(row)" icon="edit">编辑</el-button>
            <el-popconfirm
              width="220"
              confirm-button-text="确认"
              cancel-button-text="取消"
              icon="InfoFilled"
              :title="`确认删除${row.roleName}这个用户吗?`"
              @confirm="hDeleteRole(row.id)"
            >
              <template #reference>
                <el-button type="danger" icon="delete" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15]"
        background
        layout="prev, pager, next, jumper,->,sizes, total"
        :total="total"
        @size-change="hSizeChange"
        @current-change="getRoleList"
      />
    </el-card>

    <!-- 添加/修改 角色 -->
    <el-dialog v-model="dialogRole" title="添加" width="500">
      <el-form :model="roleForm">
        <el-form-item label="角色名字">
          <el-input v-model="roleForm.roleName" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogRole = false">取消</el-button>
          <el-button type="primary" @click="hSave">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配权限 -->
    <el-drawer v-model="editMenu" direction="rtl">
      <template #header>
        <h4>分配角色</h4>
      </template>
      <template #default>
        <el-tree
          ref="menuTree"
          style="max-width: 600px"
          :data="menuList"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="selecArr"
          :props="defaultProps"
        />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="editMenu = false">取消</el-button>
          <el-button type="primary" @click="doAddMenu">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { reqRoleList, reqAddEditRole, reqMenuList, reqAddMenu, reqDeleteRole } from '@/api/acl/role';
import { menuInfo } from '@/api/acl/role/type';
import { RoleInfo } from '@/api/acl/user/type';
import { ElMessage } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';

let currentPage = ref<number>(1)
let pageSize = ref<number>(10)
let total = ref<number>(0)
let roleData = ref<RoleInfo[]>([]) // 角色列表
let roleSearch = reactive<RoleInfo>({
  roleName:'',
})
let dialogRole = ref<boolean>(false) // 角色弹窗
let roleForm = reactive<RoleInfo>({
  roleName:'',
})
let editMenu = ref<boolean>(false) // 菜单弹窗
let menuList = ref<any>([]) // 菜单列表
let selecArr = ref<number[]>([]) // 菜单列表
let menuTree = ref<any>() // 菜单tree实例

// 获取roleList 
const getRoleList = async (page = 1)=> {
  currentPage.value = page
  const res = await reqRoleList(currentPage.value, pageSize.value, (roleSearch.roleName as string))
  roleData.value = res.data.records
  total.value = res.data.total
}
onMounted(()=>{
  getRoleList()
})
const hSizeChange = ()=> {
  getRoleList()
}
// 查询
const hSearch = async ()=> {
  getRoleList()
}
// 重置
const hReset = ()=> {
  roleSearch.roleName = ''
  getRoleList()
}

// 添加
const hAdd = async ()=> {
  Object.assign(roleForm, {
    id: 0,
    roleName:'',
  })
  dialogRole.value = true
}
// 编辑
const hEdit = async (row:any)=> {
  Object.assign(roleForm, {...row})
  dialogRole.value = true
}
// 保存
const hSave = async ()=> {
  const res = await reqAddEditRole(roleForm)
  if(res.code!=200) return ElMessage({type: 'error',message: roleForm.id?'更新失败':'添加失败'})
  ElMessage({type: 'success',message: roleForm.id?'更新成功':'添加成功'})
  getRoleList(roleForm.id?currentPage.value:1)
  dialogRole.value = false
}

const defaultProps = {
  children: 'children',
  label: 'name',
}
// 分配权限
const hSetRole = async (row:menuInfo)=> {
  Object.assign(roleForm, {...row})
  const res = await reqMenuList(row.id)
  if(res.code!=200) return ElMessage({type: 'error',message: '获取权限失败'})
  menuList.value = res.data
  editMenu.value = true
  selecArr.value = filterArr(menuList.value, [])
}
// 格式化菜单数组
const filterArr = (menus:any, init:any)=> {
  menus.forEach((item: any) => {
    if(item.select&&item.level==4) init.push(item.id)
    if(item.children&&item.children.length>0) {
      filterArr(item.children, init)
    }
  });
  return init
}
// 确认分配权限
const doAddMenu = async()=>{
  let arr1 = menuTree.value.getCheckedKeys()
  let arr2 = menuTree.value.getHalfCheckedKeys()
  let params = {
    permissionIdList: arr1.concat(arr2),
    userId: (roleForm.id as number),
  }
  const res = await reqAddMenu(params)
  if(res.code!=200) return ElMessage({type: 'error',message: '修改权限失败'})
  ElMessage({type: 'success',message: '修改权限成功, 重新登录后生效'})
  getRoleList(currentPage.value)
  editMenu.value = false
}
// 删除
const hDeleteRole = async (id:number)=> {
  const res = await reqDeleteRole(id)
  if(res.code!=200) return ElMessage({type: 'error',message: '删除失败'})
  ElMessage({type: 'success',message: '删除失败'})
  getRoleList(roleData.value.length>0?currentPage.value:currentPage.value-1)
}
</script>

<style lang="scss" scoped>
.roleForm{
  display: flex;
  justify-content: space-between;
  margin-bottom: -20px;
}
</style>